//
//  TTOSSManager.m
//  OSSDEMO
//
//  Created by 王洋 on 2019/9/27.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "TTOSSManager.h"
#import "UIImage+FixOrientation.h"

#import <AliyunOSSiOS/OSSService.h>





@implementation TTOSSManager

+(void)uploadPhoto:(NSMutableArray <NSData *>*)imageArray type:(NSString *)imageType FinishBlock:(finishBlock)finishBlock UploadProgress:(UploadProgress)uploadProgress FailedBlock:(FailedBlock)failedBlock{
//    if (imageArray.count == 0){
//        finishBlock(nil);
//        return;
//    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray *imagePathArray = @[].mutableCopy;
        
        for (NSData *imageD in imageArray){
            if ([imageD isKindOfClass:NSString.class]){
                [imagePathArray addObject:imageD];
                if (imagePathArray.count == imageArray.count){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        finishBlock(imagePathArray);
                    });
                }else{
                    if (uploadProgress){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            uploadProgress(imagePathArray.count*100/imageArray.count);
                        });
                    }
                }
                continue;
            }
            OSSPutObjectRequest * put = [OSSPutObjectRequest new];
            put.bucketName = OSSBUCKET_NAME;
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy/MM/dd";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            put.objectKey = [NSString stringWithFormat:@"%@/%@/iOS/%@.jpg",imageType,timeStr,[self uuidString]];
            
            
            UIImage *im = [UIImage imageWithData:imageD];
            im = [im fixOrientation];
            NSData *imageDataPng = UIImageJPEGRepresentation(im,1);
            put.uploadingData = imageDataPng; // 直接上传NSData
            [imagePathArray addObject:put.objectKey];
            OSSTask * putTask = [[self aliOSSClient] putObject:put];
            
            
            [putTask continueWithBlock:^id(OSSTask *task) {
                if (!task.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                }
                return nil;
            }];
            
            [putTask waitUntilFinished];

            if (!putTask.error) {
                if (imagePathArray.count == imageArray.count){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        finishBlock(imagePathArray);
                    });
                }else{
                    if (uploadProgress){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            uploadProgress(imagePathArray.count*100/imageArray.count);
                        });
                    }
                }
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    finishBlock(nil);
                });
                
            }
        }
    });
}

+ (OSSClient *)aliOSSClient {
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_AccessKeyId secretKey:OSS_AccessKeySecret];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =60;
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;
    
    
    [OSSLog enableLog];
    // 你的阿里地址前面通常是这种格式 ：http://oss……
    OSSClient *aliOSSClient = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credential];
    return aliOSSClient;
}

+ (NSString *)uuidString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}
@end
